package com.wjs.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wjs.gulimall.gulimallproduct.VO.Catelog2Vo;
import com.wjs.gulimall.gulimallproduct.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallproduct.dao.CategoryDao;
import com.wjs.gulimall.gulimallproduct.entity.CategoryEntity;
import com.wjs.gulimall.gulimallproduct.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 菜单树形分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2 组装成父子的树形结构
        //2.1 找到所有的一级分类
        List<CategoryEntity> treeLevel= entities.stream().filter(e -> e.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return treeLevel;
    }

    @Override
    public void deleteMenuByIds(List<Long> asList) {
        //TODO
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] getCatelogPath(Long catelogId) {
        List<Long> path=new ArrayList<>();
        List<Long> parentPath = getParentPath(catelogId, path);
        Collections.reverse(parentPath);
        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有数据
     * @param category
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'wjs'"),
            @CacheEvict(value = "category",key = "'GetJson'")
    })
    @Transactional
    public void updateCascade(CategoryEntity category) {
    this.updateById(category);
    categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

   @Cacheable(value = {"category"},key = "'wjs'")
    @Override
    public List<CategoryEntity> getCategoryoneLevel() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return categoryEntities;
    }

    /**
     * 从数据库查询三级菜单分类信息<使用本地锁></>
     * @return
     */
    public Map<String,Object> getCatalogJsonFromDbWithLocal(){
        //加锁
        synchronized (this){
            String result = redisTemplate.opsForValue().get("catalog_Json");
            if(!StringUtils.isEmpty(result)){
                Map<String, Object> map = JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
                });
                return map;
            }
            System.out.println("查询了数据库");
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            List<CategoryEntity> categoryoneLevel = getCid(selectList,0L);
            //封装数据
            Map<String, Object> collect = categoryoneLevel.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //更据一级菜单的id查询二级菜单
                List<CategoryEntity> TwoLevelEnties = getCid(selectList,v.getCatId());
                if (TwoLevelEnties != null) {
                    List<Catelog2Vo> ValueList = TwoLevelEnties.stream().map(m -> {
                        //处理数据
                        Catelog2Vo catelog2Vo = new Catelog2Vo();
                        catelog2Vo.setCatalog1Id(v.getCatId().toString());
                        catelog2Vo.setId(m.getCatId().toString());
                        catelog2Vo.setName(m.getName());
                        //根据二级菜单id查询三级菜单
                        List<CategoryEntity> ThreeLevel = getCid(selectList,m.getCatId());
                        if (ThreeLevel != null && ThreeLevel.size() > 0) {
                            List<Catelog2Vo.Catelog3Vo> list = ThreeLevel.stream().map(t -> {
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                                catelog3Vo.setCatalog2Id(m.getCatId().toString());
                                catelog3Vo.setName(t.getName());
                                catelog3Vo.setId(t.getCatId().toString());
                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(list);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                    return ValueList;
                }
                return TwoLevelEnties;
            }));
            String json = JSON.toJSONString(collect);
            redisTemplate.opsForValue().set("catalog_Json",json,1, TimeUnit.DAYS);
            return collect;
        }
    }

    /**
     * 从数据库查询三级菜单分类信息<使用Redis分布式锁></>
     * @return
     */
    public Map<String,Object> getCatalogJsonFromDbWithRedis(){
        //占分布式锁 去redis占坑 并一起设置上过期时间

        //使用uuid防止删除时删掉的是别人的锁
        String token = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token,300,TimeUnit.SECONDS);
        if(lock){
            System.out.println("获取分布式锁成功");
            //加锁成功，执行业务
            Map<String, Object> data = null;
            try {
                data = getDataFromDb();
            }finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
            }
            return data;
        }else{
            //加锁失败.....
            System.out.println("获取分布式锁失败");
            try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }
            return getCatalogJsonFromDbWithRedis();//自旋的方式
        }
    }

    /**
     * 整合redisson分布式锁
     * @return
     */
    public Map<String,Object> getCatalogJsonFromDbWithRedisson(){
            Map<String, Object> data = null;
        RLock lock = redissonClient.getLock("lock");
        lock.lock();
        try {
                data = getDataFromDb();
            }finally {
                lock.unlock();
            }
            return data;
    }

    private Map<String, Object> getDataFromDb() {
        String result = redisTemplate.opsForValue().get("catalog_Json");
        if(!StringUtils.isEmpty(result)){
            Map<String, Object> map = JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
            });
            return map;
        }
        System.out.println("查询了数据库。。。。。。。。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> categoryoneLevel = getCid(selectList,0L);
        //封装数据
        Map<String, Object> collect = categoryoneLevel.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //更据一级菜单的id查询二级菜单
            List<CategoryEntity> TwoLevelEnties = getCid(selectList,v.getCatId());
            if (TwoLevelEnties != null) {
                List<Catelog2Vo> ValueList = TwoLevelEnties.stream().map(m -> {
                    //处理数据
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(v.getCatId().toString());
                    catelog2Vo.setId(m.getCatId().toString());
                    catelog2Vo.setName(m.getName());
                    //根据二级菜单id查询三级菜单
                    List<CategoryEntity> ThreeLevel = getCid(selectList,m.getCatId());
                    if (ThreeLevel != null && ThreeLevel.size() > 0) {
                        List<Catelog2Vo.Catelog3Vo> list = ThreeLevel.stream().map(t -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(m.getCatId().toString());
                            catelog3Vo.setName(t.getName());
                            catelog3Vo.setId(t.getCatId().toString());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(list);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
                return ValueList;
            }
            return TwoLevelEnties;
        }));
        String json = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catalog_Json",json,1, TimeUnit.DAYS);
        return collect;
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.methodName")
    public Map<String, Object> GetJson() {
        System.out.println("查询了数据库。。。。。。。。。。");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> categoryoneLevel = getCid(selectList,0L);
        //封装数据
        Map<String, Object> collect = categoryoneLevel.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //更据一级菜单的id查询二级菜单
            List<CategoryEntity> TwoLevelEnties = getCid(selectList,v.getCatId());
            if (TwoLevelEnties != null) {
                List<Catelog2Vo> ValueList = TwoLevelEnties.stream().map(m -> {
                    //处理数据
                    Catelog2Vo catelog2Vo = new Catelog2Vo();
                    catelog2Vo.setCatalog1Id(v.getCatId().toString());
                    catelog2Vo.setId(m.getCatId().toString());
                    catelog2Vo.setName(m.getName());
                    //根据二级菜单id查询三级菜单
                    List<CategoryEntity> ThreeLevel = getCid(selectList,m.getCatId());
                    if (ThreeLevel != null && ThreeLevel.size() > 0) {
                        List<Catelog2Vo.Catelog3Vo> list = ThreeLevel.stream().map(t -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo();
                            catelog3Vo.setCatalog2Id(m.getCatId().toString());
                            catelog3Vo.setName(t.getName());
                            catelog3Vo.setId(t.getCatId().toString());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(list);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
                return ValueList;
            }
            return TwoLevelEnties;
        }));
        return collect;
    }

    public Map<String, Object> GetJson1() {
        /**
         * 优化查询速度
         */
        String result = redisTemplate.opsForValue().get("catalog_Json");
        if(StringUtils.isEmpty(result)){
            System.out.println("缓存不命中");
            Map<String, Object> collect = getCatalogJsonFromDbWithRedis();
            return collect;
        }
        Map<String, Object> map = JSON.parseObject(result, new TypeReference<Map<String, Object>>() {
        });
        return map;
    }

    private List<CategoryEntity> getCid(List<CategoryEntity> selectList,Long parentId) {
        List<CategoryEntity> collect = selectList.stream().filter(v -> {
                    return v.getParentCid() == parentId;
                }
        ).collect(Collectors.toList());
        return collect;
    }

    /**
     * 查询三级分类完整节点的递归方法
     * @param catelogId
     * @param path
     * @return
     */
    private List<Long> getParentPath(Long catelogId,List<Long> path){
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            getParentPath(byId.getParentCid(),path);
        }
        return path;
    }

    /**
     * 查询子菜单
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> child = all.stream().filter(entity -> {
            return entity.getParentCid() == root.getCatId();
        }).map(entity -> {
            //找到子菜单
            entity.setChildren(getChildren(entity, all));
            return entity;
        }).sorted((menu1, menu2) -> {
            //菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return child;
    }

}